<template>
  <section class="mg-auto" style="width: 1000px; margin-top: 16px">
    <!-- <FilterList /> -->
    <el-button
      v-for="item in subjects"
      :key="item.id"
      :type="item.id === showId ? 'primary' : ''"
      @click="tabChange(item.id)"
      >{{ item.name }}</el-button
    >
    <section class="mg-auto" style="width: 400px; margin-top: 16px">
      <el-input
        v-model="searchVal"
        placeholder="输入题目名字搜索"
        :prefix-icon="Search"
        @input="input"
        @change="search"
      />
    </section>
    <section style="margin-top: 16px">
      <el-button type="primary" @click="isTestPaper = !isTestPaper"
        >开始答题</el-button
      >
    </section>
    <section v-if="!isTestPaper" class="subject-list">
      <section
        v-for="item in showList"
        :key="item.id"
        class="subject-list-item"
      >
        <section
          class="subject-list-item-title pointer"
          :class="[
            hiddenTopic.includes(item.topic) ? '' : 'jt-text-overflow-hidden-1',
          ]"
          v-html="item.topic"
          @click="changeHidden(item.topic)"
        />
        <section class="subject-list-item-body" v-html="item.answer" />
      </section>
      <div class="example-pagination-block">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="prev, pager, next"
          :total="total"
        />
      </div>
    </section>
    <section v-else class="test-paper">
      <section>
        <el-button
          v-for="item in testPaperList.length"
          :key="item"
          :type="item === activeTestPaper ? 'primary' : ''"
          style="margin-top: 16px"
          @click="activeTestPaper = item"
          >{{ item }}</el-button
        >
        <section style="margin-top: 16px">
          题目：{{ testPaperList[activeTestPaper - 1].topic }}
        </section>
        <el-input
          v-model="textArerVal"
          style="margin-top: 16px"
          @change="promptChange"
          @input="answerInput"
        ></el-input>
        <section class="answer-input">{{ `第${activeTestPaper}题：` }}</section>
        <section class="answer-input" v-html="anserInput"></section>
        <el-button type="primary" style="margin-top: 16px">提交</el-button>
        <el-button style="margin-top: 16px" @click="showAnswer">
          单题验证
        </el-button>
        <el-button style="margin-top: 16px" @click="promptChange">
          提示次数：{{ promptNum }}
        </el-button>
        <section
          style="margin-top: 16px; font-size: 24px; text-align-last: left"
          v-html="promptHtml"
        />
        <section
          v-if="testPaperList[activeTestPaper - 1].isShowAnswer"
          style="margin-top: 16px; text-align: left; line-height: 1.5"
          v-html="testPaperList[activeTestPaper - 1].answer"
        />
      </section>
    </section>
  </section>
</template>

<script setup lang="ts">
// import { ElButton, ElPagination, ElInput } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { Ref, reactive, ref } from 'vue';
import subjects, {
  SubjectsListItem,
  Subject,
} from '@/views/Temp/data/subjects';
import { replaceText, repeatSearch, arrangeKeys } from '@/views/Temp/metheds';
// import FilterList from '@/views/Temp/filterList';

const total: Ref<number> = ref(1110);

const currentPage: Ref<number> = ref(1);

const pageSize: Ref<number> = ref(10);

const hiddenTopic: Array<string> = reactive([]);

const isTestPaper = ref(false);

const activeTestPaper = ref();

const promptHtml = ref('');

// 答题卡输入的答案
const textArerVal = ref('');

interface TestPaperListItem {
  topic: string;
  answer: string;
  isShowAnswer: boolean;
}

const testPaperList: Array<TestPaperListItem> = reactive([]);

// 当前显示的题库 id
const showId = ref(3);

// 切换topic 是否全部显示状态
function changeHidden(topic: string) {
  const index = hiddenTopic.findIndex((item) => item === topic);
  index === -1 ? hiddenTopic.push(topic) : hiddenTopic.splice(index, 1);
}

// 搜索input
const searchVal = ref('');

// 切换题库
function tabChange(id: number): void {
  searchVal.value = '';
  showId.value = id;
  const index = subjects.findIndex((item) => item.id === id);
  // const testPaperListItem = subjects[index].list.map(
  //   (item: SubjectsListItem): TestPaperListItem => {
  //     const result = item;

  //     result.answer = result.answer.split('\n').join('').split(' ').join('');
  //     result.answer = replaceText(result.answer, '。');
  //     result.answer = replaceText(result.answer, '；');
  //     result.answer = replaceText(result.answer, ';');
  //     return {
  //       ...item,
  //       isShowAnswer: false,
  //     };
  //   },
  // );
  const list = subjects[index].list.map((item) => {
    const result = item;
    result.answer = result.answer.split('\n').join('').split(' ').join('');
    result.answer = replaceText(result.answer, '。');
    result.answer = replaceText(result.answer, '；');
    result.answer = replaceText(result.answer, ';');
    return {
      ...item,
      isShowAnswer: false,
    };
  });
  const testPaperListItem = [...list];
  for (let i = 0; i < testPaperListItem.length; i++) {
    for (let j = testPaperListItem.length - 1; j > i; j--) {
      if (
        testPaperListItem[i].answer.length > testPaperListItem[j].answer.length
      ) {
        const temp = { ...testPaperListItem[i] };
        testPaperListItem.splice(i, 1, testPaperListItem[j]);
        testPaperListItem.splice(j, 1, temp);
      }
    }
  }
  testPaperList.splice(0, testPaperList.length, ...testPaperListItem);
  activeTestPaper.value = 1;
  search('');
}

// 显示的列表数据对象类型
interface ShowListItem {
  topic: string;
  answer: string;
  searchKey: string;
  id?: string;
}

// 显示的列表数据
const showList: Array<ShowListItem> = reactive([]);

// 搜索启动
function search(value: string) {
  const filterKeys: Array<string> = [];
  if (value.length && value.length <= 6) {
    const tempCode2: Array<string> = [];
    const tempCode3: Array<string> = [];
    const tempCode4: Array<string> = [];
    const tempCode5: Array<string> = [];
    value.split('').forEach((key, index) => {
      filterKeys.push(key);
      arrangeKeys(tempCode2, key, index, 2);
      arrangeKeys(tempCode3, key, index, 3);
      arrangeKeys(tempCode4, key, index, 4);
      arrangeKeys(tempCode5, key, index, 5);
    });
    arrangeKeys(tempCode2, 2, true);
    arrangeKeys(tempCode3, 3, true);
    arrangeKeys(tempCode4, 4, true);
    arrangeKeys(tempCode5, 5, true);
    filterKeys.push(...tempCode2, ...tempCode3, ...tempCode4, ...tempCode5);
  } else if (value.length) {
    filterKeys.push(value);
  }
  if (filterKeys.length === 0) filterKeys.push('');
  filter(filterKeys);
}

// 根据搜索字查找列表
function filter(keys: Array<string>): void {
  const result: Array<ShowListItem> = [];
  const index = subjects.findIndex((item: Subject) => item.id === showId.value);
  // 筛选匹配到关键字的 SubjectsListItem 并添加 searchKey 属性 赋值给 result
  keys.forEach((key: string) => {
    subjects[index].list.forEach((item: SubjectsListItem) => {
      if (item.topic.includes(key)) {
        if (result.length) {
          const i = result.findIndex(
            (item2: SubjectsListItem) =>
              item2.topic === item.topic && item2.id !== item.id,
          );
          i === -1
            ? result.push({ ...item, searchKey: key })
            : result.splice(i, 1, { ...item, searchKey: key });
        } else {
          result.push({ ...item, searchKey: key });
        }
      }
    });
  });
  // 关键字排序，匹配的字多排前面
  for (let i = 0; i < result.length; i++) {
    for (let j = result.length - 1; j > i; j--) {
      if (result[i].searchKey.length < result[j].searchKey.length) {
        const temp = result[i];
        result.splice(i, 1, result[j]);
        result.splice(j, 1, temp);
      }
    }
  }

  // 去除\n 符号 内容根据符号换行、 关键字标红
  result.forEach((item) => {
    item.answer = item.answer.split('\n').join('').split(' ').join('');
    item.answer = replaceText(item.answer, '。');
    item.answer = replaceText(item.answer, '；');
    item.answer = replaceText(item.answer, ';');
    item.searchKey && (item.topic = textColor(item.topic, item.searchKey));
    item.searchKey && (item.answer = textColor(item.answer, item.searchKey));
  });
  function textColor(text: string, key: string): string {
    let result: string | Array<string> = text;
    result = result.split(key);
    result = result.join(`<span class="jt-text-important">${key}</span>`);
    return result;
  }

  showList.splice(0, showList.length, ...result);
}

// 搜索输入时去除空格
function input(val: string) {
  if (val.includes(' ')) {
    searchVal.value = searchVal.value.split(' ').join('');
  }
}

const promptNum = ref(0);

const anserInput: Ref<string> = ref('');

interface ErrorIndexArrItem {
  replaceNum: number;
  index: number;
  str: string;
  type: number;
}

const errorIndexArr: Array<ErrorIndexArrItem> = [];

// 格式化答案
function answerInput() {
  promptChange(textArerVal.value, true);
}

let timer: number | null = null;

interface testStrErrLengthArrItem {
  type: number;
  nums: Array<number>;
}
// 提示后几个字
function promptChange(val: string | void, isManual: boolean | void) {
  if (timer) return;
  if (isManual) {
    const format1 = replaceText(textArerVal.value, '.');
    const format2 = replaceText(format1, '。');
    const format3 = replaceText(format2, '；');
    const format4 = replaceText(format3, ';');
    anserInput.value = `${format4}`;
    if (textArerVal.value === 'next') {
      clearFrom();
    }
    return;
  }
  const num = Math.floor(Math.random() * (8 - 5 + 1)) + 5;
  const answer: string = testPaperList[
    activeTestPaper.value - 1
  ].answer.replace(/(<section>)|(<\/section>)/g, '');
  promptNum.value++;
  const tLength = textArerVal.value.length;
  if (tLength) {
    if (answer.startsWith(textArerVal.value)) {
      errorIndexArr.splice(0, errorIndexArr.length);
      answerInput();

      if (tLength === answer.length) {
        promptNum.value--;
        promptHtml.value = '答对啦，下一题吧~';
        timer = setTimeout(() => {
          clearFrom();
          timer = null;
        }, 3000);
        return;
      }
      promptHtml.value = answer.slice(0, tLength + num);
    } else {
      let index = 0;
      const textArerValSet = textArerVal.value.split('');
      let errorNum = 0;
      errorIndexArr.splice(0, errorIndexArr.length);
      let allRN = 0;
      const testStrErrLengthArr: Array<testStrErrLengthArrItem> = [
        {
          type: 1,
          nums: [0, 1, 2, 3, 4],
        },
        {
          type: 2,
          nums: [0, 1, 2, 3, 4],
        },
        {
          type: 3,
          nums: [0, 1, 2, 3, 4],
        },
      ];
      textArerValSet.forEach((text, i) => {
        if (errorNum <= 5) {
          let replaceNum = 0;
          let type = 0;
          testStrErrLengthArr.forEach((item: testStrErrLengthArrItem) => {
            if (replaceNum) {
              return;
            }
            const errorStrNum = testStrErr(
              answer,
              textArerVal.value,
              i,
              allRN,
              item,
            );
            if (errorStrNum === -2) {
              index = i;
              return;
            }
            if (errorStrNum !== -1) {
              type = item.type;
              switch (item.type) {
                // 缺少字符 补齐
                case 1:
                  if (errorStrNum !== 0) {
                    errorNum += errorStrNum;
                    errorIndexArr.push({
                      replaceNum: errorStrNum,
                      index: i,
                      str: answer.slice(i + allRN, i + allRN + errorStrNum),
                      type,
                    });
                  }
                  if (errorIndexArr.length) {
                    const replaceNumArr = errorIndexArr.map(
                      (item) => item.replaceNum,
                    );
                    allRN = replaceNumArr.reduce(
                      (previous, next) => previous + next,
                    );
                  } else allRN = errorStrNum;
                  break;
                // 多余字符 删除
                case 2:
                  if (errorStrNum !== 0) {
                    errorNum += errorStrNum;
                    errorIndexArr.push({
                      replaceNum: errorStrNum,
                      index: i,
                      str: textArerVal.value.slice(i - errorStrNum, i),
                      type,
                    });
                  }
                  if (errorIndexArr.length) {
                    const replaceNumArr = errorIndexArr.map(
                      (item) => item.replaceNum,
                    );
                    // console.log(replaceNumArr, 'replaceNumArr');
                    allRN = replaceNumArr.reduce(
                      (previous, next) => previous + next,
                    );
                    // console.log(allRN, 'allRNallRNallRN');
                  } else allRN = errorStrNum;
                  break;
                // 错误字符 替换
                case 3:
                  if (errorStrNum !== 0) {
                    errorNum += errorStrNum;
                    errorIndexArr.push({
                      replaceNum: errorStrNum,
                      index: i,
                      str: answer.slice(i, i + errorStrNum),
                      type,
                    });
                  }
                  break;

                default:
                  break;
              }
              if (errorStrNum !== 0 && index === 0) index = i;
              textArerVal.value = textArerValSet.join('');
            }
          });
          // console.log(replaceNum);
        }
      });

      if (errorNum > 5 || errorNum === 0) {
        promptHtml.value = `
        <section>
          <span>
            ${answer.slice(0, index)}
          </span>
          <span class="jt-text-important">
            ${answer.slice(index, index + num)}
          </span>
        </section>`;
      } else {
        let allRN = 0;
        errorIndexArr.forEach((item) => {
          switch (item.type) {
            case 1:
              {
                const textArerValArr = textArerVal.value.split('');
                textArerValArr.splice(item.index + allRN, 0, item.str);
                textArerVal.value = textArerValArr.join('');
                allRN += item.replaceNum;
              }
              break;
            case 2:
              {
                const textArerValArr = textArerVal.value.split('');
                textArerValArr.splice(
                  item.index - item.replaceNum - allRN,
                  item.replaceNum,
                );
                textArerVal.value = textArerValArr.join('');
                allRN += item.replaceNum;
              }
              break;
            case 3:
              {
                const textArerValArr = textArerVal.value.split('');
                textArerValArr.splice(item.index, item.replaceNum, item.str);
                textArerVal.value = textArerValArr.join('');
              }
              break;

            default:
              break;
          }
        });
        errorIndexArr.splice(0, errorIndexArr.length);
        promptNum.value--;
        promptChange();
      }
    }
  } else {
    errorIndexArr.splice(0, errorIndexArr.length);
    promptHtml.value = answer.slice(0, num);
  }
}

// function errTextFormat(): string {
//   let result = textArerVal.value;
//   let indexAdd = 0;
//   errorIndexArr.forEach((item: ErrorIndexArrItem, index: number) => {
//     const i = item.index + indexAdd;
//     const res = result.split('');
//     res.splice(i, 1, `<span class="jt-text-important">${item.str}</span>`);
//     result = res.join('');
//     indexAdd += '<span class="jt-text-important"></span>'.length;
//   });
//   return result;
// }

/**
 *
 * @param strArr 比较的完整字符串
 * @param i 比较的索引
 * @param text 被比较的完整字符串
 * @param testStrErrLengthArrItem
 * @return 需要操作的字符长度，为0时不符合条件
 */
function testStrErr(
  strArr: string,
  text: string,
  i: number,
  allReplaceNum: number,
  testStrErrLengthArrItem: testStrErrLengthArrItem,
): number {
  let result = -1;
  switch (testStrErrLengthArrItem.type) {
    // 缺少字符 补齐
    case 1:
      testStrErrLengthArrItem.nums.forEach((num: number, index) => {
        if (result !== -1) return;
        result = strArr[i + allReplaceNum + num] === text[i] ? num : -1;
        if (
          index === testStrErrLengthArrItem.nums.length - 1 &&
          result === -1 &&
          i === text.length - 1
        ) {
          result = -2;
        }
      });
      break;
    // 多余字符 删除
    case 2:
      testStrErrLengthArrItem.nums.forEach((num: number, index) => {
        if (result !== -1) return;
        result =
          strArr[i - allReplaceNum - num] &&
          strArr[i - allReplaceNum - num] === text[i]
            ? num
            : -1;
        if (
          index === testStrErrLengthArrItem.nums.length - 1 &&
          result === -1 &&
          i === text.length - 1
        ) {
          result = -2;
        }
      });
      break;
    // 错误字符 替换
    case 3:
      testStrErrLengthArrItem.nums.forEach((num: number) => {
        if (result !== -1) return;
        result =
          strArr[i] !== text[i] &&
          strArr[i + num] &&
          strArr[i + num] === text[i + num]
            ? num
            : -1;
        // if (
        //   index === testStrErrLengthArrItem.nums.length - 1 &&
        //   result === -1 &&
        //   i === text.length - 1
        // ) {
        //   result = -2;
        // }
      });
      break;

    default:
      break;
  }
  result > 0 && console.log(result, 'result', testStrErrLengthArrItem.type);
  return result;
}

// 显示、校验答案
function showAnswer() {
  testPaperList[activeTestPaper.value - 1].isShowAnswer =
    !testPaperList[activeTestPaper.value - 1].isShowAnswer;
}

// 题目查重
function repeatTopicSearch() {
  const subjects2 = subjects.find((item) => item.id === 2);
  const subjects3 = subjects.find((item) => item.id === 3);
  const list3 =
    subjects3?.list.map((item) => {
      return item.topic;
    }) || [];
  const list2 =
    subjects2?.list.map((item) => {
      return item.topic;
    }) || [];
  const list33 =
    subjects3?.list.map((item) => {
      return item.answer;
    }) || [];
  const reg = /\n| |(结合材料回答问题)/g;
  const result3 = repeatSearch(list3, reg);
  const result2 = repeatSearch(list2, /\n| |(简述)|(判断：)|(说明：)/g);
  const result33 = repeatSearch(list33);
  console.log(result3, result33);
}

// 清除表单内容
function clearFrom() {
  textArerVal.value = '';
  activeTestPaper.value++;
  promptHtml.value = '';
  anserInput.value = '';
}

repeatTopicSearch();
{
  const topicL = subjects[1].list.map(
    (item) =>
      item.topic.replace(/(判断)|(说明)| |\n|，|。|；|“|”|：/g, '').length,
  );
  const answerL = subjects[1].list.map(
    (item) =>
      item.answer.replace(/(判断)|(说明)| |\n|，|。|；|“|”|：/g, '').length,
  );
  const length = [...topicL, ...answerL].reduce((pre, next) => pre + next);
  console.log(length, 'length');
}
tabChange(showId.value);
</script>

<style lang="scss">
@import './style/tempDemo.scss';
</style>
